﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Threading.Tasks;
using Kingdee.BOS;
using Kingdee.BOS.Util;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.Metadata.FieldElement;
using Kingdee.BOS.Core.Metadata.StateTracker;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.Bill;
using Kingdee.BOS.Orm;
using Kingdee.BOS.Orm.Metadata;
using Kingdee.BOS.Orm.Metadata.DataEntity;
using Kingdee.BOS.Core.Metadata.EntityElement;
using Kingdee.BOS.Core.DynamicForm.PlugIn.ControlModel;
using Kingdee.BOS.JSON;
using Kingdee.BOS.Core.Const;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.Metadata.BarElement;
using Kingdee.BOS.Core.SqlBuilder;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args.UnitTest;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.App;
using Kingdee.BOS.App.Data;

namespace Sincetech.K3.SCM.Common
{
    /// <summary>
    /// 非库存业务单据：单据插件
    ///  采购订单、采购订单变更单、采购收料单、退料申请单
    ///  销售订单、销售订单变更单、发货通知单、退货通知单
    /// </summary>
    public class Business_Bill : AbstractDynamicFormPlugIn
    {
        //物料编码
        string strValue = "";
        //物料代码
        string F_st_MaterialNo = "";

        #region DataChanged-值更新事件
        /// <summary>
        /// 值更新事件
        /// </summary>
        /// <param name="e"></param>
        public override void DataChanged(DataChangedEventArgs e)
        {
            base.DataChanged(e);
            #region
            //var a = metadata.BusinessInfo.GetField("FMaterialId");
            switch (e.Field.Key.ToString())
            {
                case "FMaterialId":                //物料编码
                    //获取元数据服务
                    IMetaDataService metadataService = Kingdee.BOS.App.ServiceHelper.GetService<IMetaDataService>();
                    //获取物料单据元数据
                    //FormMetadata materialMetadata = metadataService.Load(this.Context,"BD_Material") as FormMetadata;
                    FormMetadata materialMetadata = (FormMetadata)Kingdee.BOS.ServiceHelper.MetaDataServiceHelper.Load(this.View.Context, "BD_MATERIAL");
                    //获取保存服务
                    //ISaveService saveService = Kingdee.BOS.App.ServiceHelper.GetService<ISaveService>();
                    //获取加载数据服务
                    IViewService viewService = Kingdee.BOS.App.ServiceHelper.GetService<IViewService>();
                    DynamicObject material = (DynamicObject)this.Model.GetValue(e.Field);
                    string materialId = Convert.ToString(material["Id"]);
                    DynamicObject[] objs = viewService.Load(
                        this.Context,
                        new object[] { materialId },
                        materialMetadata.BusinessInfo.GetDynamicObjectType());
                    strValue = Convert.ToString(objs[0]["Id"]);
                    //F_st_MaterialNo = "";
                    Entity subEntity = this.View.BillBusinessInfo.GetEntity("FSubEntity");
                    //object obj = this.View.Model.GetEntityDataObject(subEntity).Parent;
                    //F_st_RowNo = 0;
                    break;
            }
            #endregion
        }
        #endregion

        #region AfterBindData-绑定数据后触发
        /// <summary>
        /// 绑定数据后触发
        /// </summary>
        /// <param name="e"></param>
        public override void AfterBindData(EventArgs e)
        {
            base.AfterBindData(e);
        }
        #endregion

        #region EntryCellFocued-单元格聚焦（单击，回车）事件
        /// <summary>
        /// 单据体单元格获取焦点时触发
        /// </summary>
        /// <param name="e"></param>
        public override void EntryCellFocued(EntryCellFocuedEventArgs e)
        {
            //base.EntryCellFocued(e);
            #region

            //DynamicObject material = (DynamicObject)this.Model.GetValue("FMaterialId");
            //if (material != null)
            //{
            //    string materialId = Convert.ToString(material["Id"]);

            //    string sql = string.Format(@"SELECT F_ST_USEPAIRQTYFLAG FROM T_BD_MATERIAL WHERE FMATERIALID = {0}))", material["Id"]);
            //    using (IDataReader dr = DBUtils.ExecuteReader(this.Context, sql))
            //    {
            //        if (dr["F_ST_USEPAIRQTYFLAG"].ToString() == "true")
            //        {

            //        }

            //    }
            //}
            //当采购单位为双的时候，弹出双数明细子窗体
            DynamicObject unit = this.View.Model.GetValue("F_st_UnitID", e.NewRow) as DynamicObject;
            if (unit != null)
            {
                if (e.NewFieldKey.ToUpper() == "F_ST_QTY" && unit["Name"].ToString() == "双")
                {
                    DynamicFormShowParameter showParam = new DynamicFormShowParameter();
                    //判断子单据双数明细是否有赋值，有赋值，则把当前子单据的数据填入双数明细的子窗体中
                    SubEntryEntity subEntity = this.View.BusinessInfo.GetEntity("FSubEntity") as SubEntryEntity;
                    EntryEntity Entity = subEntity.ParentEntity;
                    //获取父单据体的动态对象集合
                    DynamicObjectCollection entryRows = this.View.Model.GetEntityDataObject(Entity);
                    DynamicObject currRow = entryRows[e.NewRow];
                    // 取当前行的子单据体数据集合
                    DynamicObjectCollection subEntityRows = subEntity.DynamicProperty.GetValue(currRow) as DynamicObjectCollection;
                    //Entity subEntity = this.View.BillBusinessInfo.GetEntity("FSubEntity");
                    //DynamicObjectCollection subEntityRows = this.View.Model.GetEntityDataObject(subEntity);

                    //单据名，不能使用继承的单据名，原因未知
                    showParam.FormId = "567d468c-e088-44f0-80a0-5e18efea79ee";
                    //该单据的主键值，新建时可以不填
                    //showParam.PKey = "100001";
                    //单据才设置状态，动态表单没有状态
                    //showParam.Status = OperationStatus.ADDNEW;
                    showParam.ParentPageId = this.View.PageId;
                    showParam.OpenStyle.ShowType = ShowType.Floating;
                    //showParam.OpenStyle.ShowType = ShowType.InContainer;
                    //传递特殊属性到目标模型
                    //目标模型可以在其表单插件中的OnInitial事件中获取这些参数
                    //传递物料编码
                    DynamicObject MATERIAL = currRow["MaterialId"] as DynamicObject; 
                    showParam.CustomParams.Add("FMATERIALID", MATERIAL["Id"].ToString());
                    showParam.CustomParams.Add("F_st_MaterialNo", MATERIAL["Number"].ToString());
                    showParam.CustomParams.Add("F_st_RowNo", (e.NewRow + 1).ToString());
                    showParam.CustomComplexParams.Add("SubEntityRows", subEntityRows);
                    //获取当前行的数量值

                    showParam.CustomParams.Add("PtotalNum", this.Model.GetValue("F_ST_QTY", e.NewRow).ToString());

                    this.View.ShowForm(showParam, r => this.Onclos(r));
                }
            }
            #endregion
        }
        #endregion

        /// <summary>
        /// 数量字段双击事件
        /// </summary>
        /// <param name="e"></param>
        //public override void EntityRowDoubleClick(EntityRowClickEventArgs e)
        //{
        //    if (e.ColKey.ToUpper() == "FQTY")
        //    {

        //        DynamicFormShowParameter showParam = new DynamicFormShowParameter();
        //        //单据名，不能使用继承的单据名，原因未知
        //        showParam.FormId = "567d468c-e088-44f0-80a0-5e18efea79ee";
        //        //该单据的主键值，新建时可以不填
        //        //showParam.PKey = "100001";
        //        //单据才设置状态，动态表单没有状态
        //        //showParam.Status = OperationStatus.ADDNEW;
        //        showParam.ParentPageId = this.View.PageId;
        //        showParam.OpenStyle.ShowType = ShowType.Floating;
        //        //showParam.OpenStyle.ShowType = ShowType.InContainer;

        //        //传递特殊属性到目标模型
        //        //目标模型可以在其表单插件中的OnInitial事件中获取这些参数
        //        //传递物料编码
        //        showParam.CustomParams.Add("FMATERIALID", strValue);
        //        showParam.CustomParams.Add("F_st_MaterialNo", F_st_MaterialNo);
        //        showParam.CustomParams.Add("F_st_RowNo", F_st_RowNo);
        //        //showParam.CustomComplexParams.Add("parentView", this.View);

        //        this.View.ShowForm(showParam);

        //        this.View.ShowForm(showParam, r => this.Onclos(r));
        //    }
        //}

        #region Onclos-自定义回调函数，用于把子窗体返回数据给父窗体
        /// <summary>
        /// 回调函数,返回数据
        /// </summary>
        /// <param name="result"></param>
        public void Onclos(FormResult result)
        {
            #region
            PairDetailRtnData pairDetailRtnData = (PairDetailRtnData)result.ReturnData;
            if (pairDetailRtnData != null)
            {
                //单据体
                DynamicObjectCollection docContacts = pairDetailRtnData.DynObjCollection;
                //总双数字段
                int qty = pairDetailRtnData.totalNum;
                //行号
                int row = pairDetailRtnData.rowNum;
                BusinessInfo info = this.View.OpenParameter.FormMetaData.BusinessInfo;

                #region 父单据体字段业务数量赋值

                this.View.Model.SetValue("F_st_Qty", null, row);

                #endregion

                #region 子单据体双数明细赋值
                //获取当前界面双数明细的单据

                Entity resultEntity = info.GetEntity("FSubEntity");
                //this.View.Model.DeleteEntryData("FSubEntity");
                //this.View.Model.DeleteEntryRow("FSubEntity", 1);
                Entity subEntity = this.View.BillBusinessInfo.GetEntity("FSubEntity");
                DynamicObjectCollection subEntityRows = this.View.Model.GetEntityDataObject(subEntity);
                //删除双数明细的全部行
                subEntityRows.Clear();
                //循环填充子窗体传过来的值
                for (int i = 0; i < docContacts.Count; i++)
                {
                    DynamicObject doc = docContacts[i];
                    DynamicObject bdInfo = doc["F_st_Size"] as DynamicObject;
                    string bdInfo1 = (string)doc["F_st_LR"];
                    decimal bdInfo2 = (decimal)doc["F_st_Qty"];
                    //新建行
                    View.Model.CreateNewEntryRow("FSubEntity");
                    int iRow = View.Model.GetEntryCurrentRowIndex("FSubEntity");
                    View.Model.SetValue("F_ST_SIZE", bdInfo["id"].ToString(), iRow);
                    View.Model.SetValue("F_ST_LR", bdInfo1, iRow);
                    View.Model.SetValue("F_ST_PAIRDETAILQTY", bdInfo2, iRow);

                }
                //给相应的父单据的行的销售数量赋值
                View.Model.SetValue("F_ST_QTY", qty, row);
                #endregion

                this.View.UpdateView("FSubEntity");
                //this.View.Refresh();
            }
            #endregion
        }
        #endregion

    }
}
